Nuxt3 有個很重要的特性,那就是 自動引入 (Auto Imports),大幅增加你的開發者體驗

來看看我們再寫 Vue 常發生的事
我要用 component !!  import component
<script>
//匯入  Modal、cart、toast
import ModalItem from '.././components/ModalItem.vue'
import CartItem from '.././components/CartlItem.vue'
import ToastItem from '../components/ToastItem.vue'
//option api 還要再額外匯入元件
export default {
  data() {
    return {
      }
    }
  },
  components: {
    ModalItem, 
    CartItem,
    ToastItem,
  },
}
</script>
我要用 ref !! import ref
import { ref }  from 'vue'
我要用 watch !! import watch
import { watch } from 'vue'
我要用 computed !! import watch
import { computed } from 'vue'
import ! import ! import 瘋狂的 import
忘記 import 還會報錯,結果找老半天發現忘了 import (眼神死
最後會發現 vue 專案就會變成這樣
//匯入  Modal、cart、toast
import ModalItem from '.././components/ModalItem.vue'
import CartItem from '.././components/CartlItem.vue'
import ToastItem from '../components/ToastItem.vue'
import { ref }  from 'vue'
import { watch } from 'vue'
import { computed } from 'vue'
... 
...
...
...
//可能還有更多
滿滿的 import ,就會覺得很惱人,有使用到什麼就要對應的 import 匯入,雖然可以一目了然的看到匯入哪些,但是有時候撰寫程式碼時,光是引入就很繁瑣,而Nuxt3的其中一個特性就是自動引入 (Auto Imports) 元件及常用的 vue 。
那 Nuxt 有哪些會幫我們自動引入呢 ?
Nuxt 官方 Composables、Components常用的 Vue api 引入常用的 ref、computed 、watch 等api,以及 Vue 生命周期相關的(onMounted、onUpdated ...)。  /* 自動引入 ref() 、 computed()  auto-imported */
  const count = ref(1)
  const double = computed(() => count.value * 2)
資料夾自動引入包含 components、composables、utils,比較特別的是 components 除了會依照資料夾引入外,還額外第二層可以引入資料夾自動引入範例(一) : 元件一般自動引入
| components/
--| TheHeader.vue
--| TheFooter.vue
// components 下 header、footer 會自動引入無須再額外引入
<template>
  <div>
    <TheHeader />
    <slot />
    <TheFooter />
  </div>
</template>
資料夾自動引入範例(二) : 元件目錄自動引入
| components/
--| base/
----| foo/
------| Button.vue
//資料夾大寫引入,可以直接辨識是在哪個資料夾的 component
<template>
    <BaseFooButton /> 
</template>
自動引入省去了惱人的 import ,讓我們可以更專注於專案開發,但是相對的也是有缺點,有時候import 引入可以讓我們更清楚知道這頁面使用哪些元件,雖然有 Devtools 可以幫助我們,但是每個人的開發習慣不同,可以依照需求自訂自動引入及關閉自動引入。
nuxt.config 關閉自動引入方法
自動引入預設開啟,使用nuxt.config裡的imports.autoImport方法,如果要關閉再nuxt.config裡將選項改為false即可。
export default defineNuxtConfig({
  imports: {
    autoImport: false //改為false
  }
})